package com.sk.weichat.ui.message;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.githang.statusbar.StatusBarCompat;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageEventClickable;
import com.sk.weichat.adapter.MessageEventRequert;
import com.sk.weichat.adapter.MessageLocalVideoFile;
import com.sk.weichat.adapter.MessageUploadChatRecord;
import com.sk.weichat.adapter.MessageVideoFile;
import com.sk.weichat.audio_x.VoicePlayer;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.Contacts;
import com.sk.weichat.bean.EventChatAllowSendMsg;
import com.sk.weichat.bean.EventChatRemoveBlack;
import com.sk.weichat.bean.EventTransfer;
import com.sk.weichat.bean.EventUploadCancel;
import com.sk.weichat.bean.EventUploadFileRate;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.IsBindAlipayBean;
import com.sk.weichat.bean.PrivacySetting;
import com.sk.weichat.bean.PublicMenu;
import com.sk.weichat.bean.VideoFile;
import com.sk.weichat.bean.collection.CollectionEvery;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.bean.redpacket.EventRedReceived;
import com.sk.weichat.bean.redpacket.EventRedReceivedStatus;
import com.sk.weichat.bean.redpacket.RedDialogBean;
import com.sk.weichat.bean.redpacket.RedpacketDetailBean;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.db.dao.VideoFileDao;
import com.sk.weichat.downloader.Downloader;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.mvp.contract.ChatContract;
import com.sk.weichat.mvp.presenter.ChatBottomPresenter;
import com.sk.weichat.mvp.presenter.ChatContentPresenter;
import com.sk.weichat.mvp.presenter.ChatPresenter;
import com.sk.weichat.pay.TransferMoneyActivity;
import com.sk.weichat.pay.TransferMoneyDetailActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.contacts.SendContactsActivity;
import com.sk.weichat.ui.dialog.CreateCourseDialog;
import com.sk.weichat.ui.groupchat.TabSelectContactsActivity;
import com.sk.weichat.ui.map.MapPickerActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.me.SelectCollectionActivity;
import com.sk.weichat.ui.me.redpacket.RedpacketRouter;
import com.sk.weichat.ui.me.redpacket.SendRedPacketActivity1;
import com.sk.weichat.ui.me.wallet.IdentityAuthenticationActivity;
import com.sk.weichat.ui.message.single.PersonSettingActivity;
import com.sk.weichat.ui.mucfile.AddMucFileActivity2;
import com.sk.weichat.util.ChangeBackgroundHelper;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.HtmlUtils;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.skin.Colorful;
import com.sk.weichat.video.MessageEventGpu;
import com.sk.weichat.video.VideoRecorderActivity;
import com.sk.weichat.view.ChatBottomView;
import com.sk.weichat.view.ChatBottomView.ChatBottomListener;
import com.sk.weichat.view.ChatContentView;
import com.sk.weichat.view.ChatContentView.MessageEventListener;
import com.sk.weichat.view.NoDoubleClickListener;
import com.sk.weichat.view.SelectCardPopupWindow;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.TipDialog;
import com.sk.weichat.view.chatHolder.MessageEventClickFire;
import com.sk.weichat.view.redDialog.RedDialog;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JVCideoPlayerStandardforchat;
import fm.jiecao.jcvideoplayer_lib.MessageEvent;
import okhttp3.Call;
import pl.droidsonroids.gif.GifDrawable;

import static com.sk.weichat.broadcast.MsgBroadcast.ACTION_REDPACKET_MSG_UPDATE;
import static com.sk.weichat.broadcast.OtherBroadcast.RECEIVER_ACTION_FINISH_A;
import static com.sk.weichat.ui.me.SelectCollectionActivity.SelectCollectionKey;
import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.SELECT_FILES;

/**
 * 单聊界面
 */
public class ChatActivity extends BaseActivity implements
        NewFriendListener, MessageEventListener, ChatBottomListener, ChatMessageListener, ChatContract.ChatView,
        SelectCardPopupWindow.SendCardS, PermissionUtil.OnRequestPermissionsResultCallbacks, View.OnClickListener, ChangeBackgroundHelper.OnBackgroundChangeListener {

    private static final int REQUEST_MICROPHONE_CODE = 1005;
    private static final int REQUEST_CAMERA_CODE = 1008;
    public static final String FRIEND = "friend";
    /*输入红包金额的返回*/
    public static final int REQUEST_CODE_SEND_RED = 13;     // 发红包
    public static final int REQUEST_CODE_SEND_RED_PT = 10;  // 普通红包返回
    public static final int REQUEST_CODE_SEND_RED_KL = 11;  // 口令红包返回
    public static final int REQUEST_CODE_SEND_RED_PSQ = 12; // 拼手气红包返回
    // 发送联系人，
    public static final int REQUEST_CODE_SEND_CONTACT = 21;
    /***********************
     * 拍照和选择照片
     **********************/
    private static final int REQUEST_CODE_CAPTURE_PHOTO = 1;
    private static final int REQUEST_CODE_PICK_PHOTO = 2;
    private static final int REQUEST_CODE_SELECT_VIDEO = 3;
    private static final int REQUEST_CODE_SEND_COLLECTION = 4;// 我的收藏 返回
    private static final int REQUEST_CODE_SELECT_Locate = 5;
    private static final int REQUEST_CODE_QUICK_SEND = 6;
    private static final int REQUEST_CODE_SELECT_FILE = 7;
    public static final int REQUEST_CODE_SEND_CARD = 8;//发送名片

    /*******************************************
     * 自动同步其他端收发的消息 && 获取漫游聊天记录
     ******************************************/
    @SuppressWarnings("unused")
    private ChatContentView mChatContentView;
    // 存储聊天消息
    private List<ChatMessage> mChatMessages;
    private ChatBottomView mChatBottomView;
    private ImageView mChatBgIv;// 聊天背景
    private AudioManager mAudioManager;
    // 当前聊天对象
    private Friend mFriend;
    private String mLoginUserId;
    private String mLoginNickName;
    private boolean isSearch;
    private double mSearchTime;
    // 消息转发
    private String instantMessage;
    // 是否为通知栏进入
    private boolean isNotificationComing;
    private TextView mTvTitleLeft;
    // 在线 || 离线...
    private TextView mTvTitle;
    // 是否为阅后即焚
    private int isReadDel;
    private long mMinId = 0;
    private Uri mNewPhotoUri;
    private HashSet<String> mDelayDelMaps = new HashSet<>();// 记录阅后即焚消息的 packedid
    private ChatMessage replayMessage;
    private RedDialog mRedDialog;
    private ChatPresenter mChatPresenter;
    private ChatBottomPresenter mChatBottomPresenter;
    private ChatContentPresenter mChatContentPresenter;
    private RelativeLayout mLayoutAttention;
    private TextView mTvAttentionTitle;
    private TextView mTvAttentionContent;
    private String mAddhaoyouid;
    private int mFriendState;
    private SmartRefreshLayout mRefreshLayout;
    private TextView mTvOnline;

    private RefreshBroadcastReceiver mRefreshBroadcastReceiver;
    private boolean mIsOnlyAllowAttention = false;

    public static void start(Context ctx, Friend friend) {
        Intent intent = new Intent(ctx, ChatActivity.class);
        intent.putExtra(ChatActivity.FRIEND, friend);
        ctx.startActivity(intent);
    }


    private class RefreshBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(RECEIVER_ACTION_FINISH_A)) {  /*转发成功 关闭页面 */
                finish();
            } else if (action.equals(MsgBroadcast.ACTION_MSG_SHARE)) {
                ChatMessage mLastChatMessage = ChatMessageDao.getInstance().getLastChatMessage(mLoginUserId, mFriend.getUserId());
                mChatMessages.add(mLastChatMessage);
                mChatContentView.notifyDataSetInvalidated(true);
            } else if (action.equals(ACTION_REDPACKET_MSG_UPDATE)) {//红包发送成功通知  更改状态
                String PacketId = intent.getStringExtra("PacketId");
                for (int i = 1; i < mChatMessages.size(); i++) {
                    ChatMessage msg = mChatMessages.get(i);
                    if (PacketId.equals(msg.getPacketId())) {
                        msg.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
                        mChatContentView.notifyDataSetInvalidated(mChatMessages.size() - 1);
                        break;
                    }
                }
            } else if (action.equals(MsgBroadcast.ACTION_REDPACKET_BIND_ALIPAY)) {//支付宝绑定成功
                ChatMessage message = intent.getParcelableExtra("ChatMessage");
                clickRedpacket(message);
            } else if (action.equals(MsgBroadcast.ACTION_MSG_UI_UPDATE)) {//刷新页面 被取消关注 移粉 等收到通知更新ui
                onResume();
            }
        }
    }


    // 点击红包 查询红包状态
    public void clickRedpacket(ChatMessage message) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(mContext);
        }
        final String token = CoreManager.requireSelfStatus(mContext).accessToken;
        final String redId = message.getObjectId();
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", token);
        params.put("id", redId);
        HttpUtils.post().url(CoreManager.requireConfig(mContext).RED_PACKET_STATUS)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {

                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        DialogHelper.dismissProgressDialog();

                        if (result.getResultCode() == 1) {
                            if (result.getData() != null) {
                                // 当resultCode==1时，表示可领取
                                // 当resultCode==0时，表示红包已过期、红包已退回、红包已领完
                                RedpacketDetailBean mRedpacketDetailBean = result.getData();
                                EventBus.getDefault().post(new EventRedReceivedStatus(message.getPacketId(), mRedpacketDetailBean.getStatus()));
                                if (mRedpacketDetailBean.getStatus() == 0) {//未领取  判断是否绑定支付宝
                                    isBindAlipay(message, mRedpacketDetailBean);
                                } else {
                                    RedpacketRouter.route(mContext, CoreManager.getSelf(mContext).getUserId(), message.getPacketId(), mRedpacketDetailBean);
                                }
                            }
                        } else {
                            DialogHelper.dismissProgressDialog();
                            Toast.makeText(mContext, result.getResultMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }

    /**
     * @author: czl
     * @description 是否绑定支付宝
     * @date: 2019/10/9 11:10
     */
    public void isBindAlipay(ChatMessage message, RedpacketDetailBean mRedpacketDetailBean) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", CoreManager.getSelfStatus(mContext).accessToken);
        HttpUtils.post().url(CoreManager.getConfig(mContext).IS_BIND_ALIPAY)
                .params(params)
                .build()
                .execute(new BaseCallback<IsBindAlipayBean>(IsBindAlipayBean.class) {
                    @Override
                    public void onResponse(ObjectResult<IsBindAlipayBean> result) {
                        if (result.getResultCode() == 1) {
                            IsBindAlipayBean mIsBindAlipayBean = result.getData();
                            if (mIsBindAlipayBean.getState().equals("BINDING")) {//已绑定支付宝
                                RedpacketRouter.route(mContext, CoreManager.getSelf(mContext).getUserId(), message.getPacketId(), mRedpacketDetailBean);
                            } else {//没绑定支付宝 跳转至绑定支付宝页面
                                mContext.startActivity(new Intent(mContext, IdentityAuthenticationActivity.class)
                                        .putExtra("aliPayNickName", "").putExtra("isReceiveRedpack", true).putExtra("ChatMessage", message));
                            }
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showToast(mContext, e.toString());
                    }
                });
    }


    /**
     * 通知聊天页面关闭，
     * 比如被删除被拉黑，
     *
     * @param content 弹Toast的内容，
     */
    public static void callFinish(Context ctx, String content, String toUserId) {
        Intent intent = new Intent();
        intent.putExtra("content", content);
        intent.putExtra("toUserId", toUserId);
        intent.setAction(com.sk.weichat.broadcast.OtherBroadcast.TYPE_DELALL);
        ctx.sendBroadcast(intent);
    }

    private boolean once = false;
    private int originalHeight = 0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        mLoginUserId = coreManager.getSelf().getUserId();
        mLoginNickName = coreManager.getSelf().getNickName();
        if (getIntent() != null) {
            mFriend = (Friend) getIntent().getSerializableExtra(AppConstant.EXTRA_FRIEND);
            //获取最新的关系
            mFriend = FriendDao.getInstance().getFriend(mFriend.getOwnerId(), mFriend.getUserId());
            isSearch = getIntent().getBooleanExtra("isserch", false);
            if (isSearch) {
                mSearchTime = getIntent().getDoubleExtra("jilu_id", 0);
            }
            instantMessage = getIntent().getStringExtra("messageId");
            isNotificationComing = getIntent().getBooleanExtra(Constants.IS_NOTIFICATION_BAR_COMING, false);
        }
        mAudioManager = (AudioManager) getSystemService(android.app.Service.AUDIO_SERVICE);
        Downloader.getInstance().init(MyApplication.getInstance().mAppDir + File.separator + mLoginUserId
                + File.separator + Environment.DIRECTORY_MUSIC);
        initView();
        // 添加新消息来临监听
        ListenerManager.getInstance().addChatMessageListener(this);
        // 注册EventBus
        EventBus.getDefault().register(this);
        if (mFriend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
            mChatBottomPresenter.initSpecialMenu();
        } else {
            // 获取聊天对象当前的在线状态
            mChatBottomPresenter.initFriendState();
        }

        mRefreshBroadcastReceiver = new RefreshBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RECEIVER_ACTION_FINISH_A);
        intentFilter.addAction(ACTION_REDPACKET_MSG_UPDATE);//发红包消息
        intentFilter.addAction(MsgBroadcast.ACTION_MSG_SHARE);//分享给自己广播
        intentFilter.addAction(MsgBroadcast.ACTION_REDPACKET_BIND_ALIPAY);//接收红包绑定支付宝成功返回
        intentFilter.addAction(MsgBroadcast.ACTION_MSG_UI_UPDATE);//刷新页面

        registerReceiver(mRefreshBroadcastReceiver, intentFilter);

        //设置背景图监听,用getApplicationContext没有延迟
        ChangeBackgroundHelper.registOnBackgroundChangeListener(getApplicationContext(), this, coreManager.getSelf().getUserId() + mFriend.getUserId());
        RelativeLayout bootomChatMenu = findViewById(R.id.rl_chat_meun);
        bootomChatMenu.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int[] location = new int[2];
                bootomChatMenu.getLocationInWindow(location);
                if (!once) {
                    once = true;
                    originalHeight = location[1];
                }
                Colorful.Builder builder = new Colorful.Builder(ChatActivity.this)
                        .imageViewbgDrawable(R.id.voice_img_btn, R.attr.chat_bottom_bar_voice)//底部语音按钮图标
                        .imageViewbgDrawable(R.id.img_bottom_photo, R.attr.chat_bottom_bar_picture)//更多图标
                        .imageViewbgDrawable(R.id.img_bottom_camera, R.attr.chat_bottom_bar_camera)//底部拍照按钮图标
                        .imageViewbgDrawable(R.id.emotion_btn, R.attr.chat_bottom_bar_emoji)//emoji图标
                        .imageViewbgDrawable(R.id.more_btn, R.attr.chat_bottom_bar_more)//更多图标
                        .imageViewbgDrawable(R.id.img_msg_send, R.attr.chat_bottom_bar_send);//发送消息按钮
                if (location[1] == originalHeight) {
                    //底部菜单收起
                    if (ChangeBackgroundHelper.isSetBackground(mContext, coreManager.getSelf().getUserId() + mFriend.getUserId())) {
                        //设置了背景图，底部图标变成白色的
                        StatusBarCompat.setLightStatusBar(getWindow(), false);
                        Colorful mColorful = builder.backgroundDrawable(R.id.mergerStatus, R.attr.chat_toolbar_bg)//标题栏背景
                                .backgroundDrawable(R.id.rl_chat_meun, R.attr.chat_bottom_bg)//底部背景
                                .create();
                        mColorful.setTheme(R.style.chat_style_light);
                    }
                    mChatBottomView.setTag(null);
                } else {
                    //弹出
                    if (ChangeBackgroundHelper.isSetBackground(mContext, coreManager.getSelf().getUserId() + mFriend.getUserId())) {
                        Colorful mColorful = builder
                                .backgroundColor(R.id.rl_chat_meun, R.attr.chat_bottom_bg)//底部背景
                                .create();
                        mColorful.setTheme(R.style.chat_style_dark);
                        //设置选中的图标
                        Object obj = mChatBottomView.getTag();
                        if (obj != null && obj instanceof HashMap) {
                            HashMap<Integer, Integer> viewmap = (HashMap<Integer, Integer>) obj;
                            if (viewmap != null) {
                                Iterator<Map.Entry<Integer, Integer>> itr = viewmap.entrySet().iterator();
                                if (itr.hasNext()) {
                                    Map.Entry<Integer, Integer> entry = itr.next();
                                    ImageView imageView = mChatBottomView.findViewById(entry.getKey());
                                    imageView.setImageDrawable(getResources().getDrawable(entry.getValue()));
                                }
                            }
                        }
                    }
                }
            }
        });
    }


    private void initView() {
        mChatMessages = new ArrayList<>();
        mChatPresenter = new ChatPresenter(this, coreManager);
        mChatPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
        mChatContentPresenter = new ChatContentPresenter(this, coreManager);
        mChatContentPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
        mChatBottomPresenter = new ChatBottomPresenter(this, coreManager);
        mChatBottomPresenter.bandData(mFriend, mLoginUserId, mLoginNickName, mChatMessages);

        mChatBottomView = (ChatBottomView) findViewById(R.id.chat_bottom_view);
        mChatContentView = (ChatContentView) findViewById(R.id.chat_content_view);
        initActionBar();
        if (mFriend.getIsDevice() == 1) {
            mChatBottomView.setEquipment(true);
            mChatContentView.setChatListType(ChatContentView.ChatListType.DEVICE);
        }
        initHeadAttention();
        initBottomView();
        initContentView();
        // 刷新用户余额
        CoreManager.updateMyBalance();
        // 是否为通知栏进入
        if (isNotificationComing) {
            Intent intent = new Intent();
            intent.putExtra(AppConstant.EXTRA_FRIEND, mFriend);
            intent.setAction(Constants.NOTIFY_MSG_SUBSCRIPT);
            sendBroadcast(intent);
        } else {
            FriendDao.getInstance().markUserMessageRead(mLoginUserId, mFriend.getUserId());
        }

        mChatContentPresenter.loadContentData(true, isSearch, mSearchTime);
        // 自动同步其他端的聊天记录
        mChatContentPresenter.synchronizeChatHistory();
//        if (mFriend.getDownloadTime() < mFriend.getTimeSend()) {
//
//        }
        //xmpp广播监听
        mChatPresenter.registerXMPPReceiver(this);
    }

    private void initHeadAttention() {
        mLayoutAttention = findViewById(R.id.layout_chat_attention);
        mTvAttentionTitle = findViewById(R.id.tv_chat_attention_title);
        mTvAttentionContent = findViewById(R.id.tv_chat_attention_content);

        findViewById(R.id.layout_chat_attention_btn).setOnClickListener(this);
        findViewById(R.id.img_chat_attention_del).setOnClickListener(this);

    }

    private void updateHeadAttention() {
        //获取最新的关系
        mFriend = FriendDao.getInstance().getFriend(mFriend.getOwnerId(), mFriend.getUserId());
        if (mFriend.getAttentionTag() == 1 || mFriend.getStatus() == Friend.STATUS_FRIEND
                || mFriend.getStatus() == Friend.STATUS_SYSTEM
                || mFriend.getStatus() == Friend.STATUS_ATTENTION) {//客服、好友、关注时隐藏关注头部
            mLayoutAttention.setVisibility(View.GONE);
        } else if (mFriend.getStatus() == Friend.STATUS_BE_ATTENTION) {//被关注
            mLayoutAttention.setVisibility(View.VISIBLE);
            mTvAttentionTitle.setText("对方关注了你，是否关注对方?");
            mTvAttentionContent.setText("关注后彼此有机会听到对方的声音");
        } else {
            mLayoutAttention.setVisibility(View.VISIBLE);
            mTvAttentionTitle.setText("是否关注对方?");
            mTvAttentionContent.setText("相互关注才能成为好友");
        }
    }

    public int getNumTotal() {
        int numMessage = FriendDao.getInstance().getMsgUnReadNumTotal(coreManager.getSelf().getUserId());
        Friend newFriend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE);//关系通知未读数
        int unReadNumTotal = GroupMessageDao.getInstance().getGroupMsgUnReadNumTotal(coreManager.getSelf().getUserId());
        numMessage += newFriend.getUnReadNum() + unReadNumTotal;
        return numMessage;
    }

    /**
     * 初始化ActionBar与其点击事件
     */
    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doBack();
            }
        });

        TextView tvNumLeft = (TextView) findViewById(R.id.tv_num_left);
        int numTotal = getNumTotal();
        if (numTotal < 1) {
            tvNumLeft.setVisibility(View.GONE);
        } else if (numTotal > 99) {
            tvNumLeft.setVisibility(View.VISIBLE);
            tvNumLeft.setText("99+");
        } else {
            tvNumLeft.setVisibility(View.VISIBLE);
            tvNumLeft.setText(numTotal + "");
        }

        mTvTitleLeft = (TextView) findViewById(R.id.tv_title_left);
        mTvTitleLeft.setVisibility(View.GONE);
        mTvTitleLeft.setText(getString(R.string.cancel));
        mTvTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moreSelected(false, 0);
            }
        });
        mTvOnline = (TextView) findViewById(R.id.tv_online);
        mTvTitle = (TextView) findViewById(R.id.tv_title_center);
        String remarkName = mFriend.getRemarkName();
        if (TextUtils.isEmpty(remarkName)) {
            mTvTitle.setText(mFriend.getNickName());
        } else {
            mTvTitle.setText(remarkName);
        }

        ImageView mMore = (ImageView) findViewById(R.id.iv_title_right);
        mMore.setImageResource(R.drawable.ic_chat_more);
        mMore.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                mChatBottomView.reset();
                mChatBottomView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(ChatActivity.this, PersonSettingActivity.class);
                        intent.putExtra("ChatObjectId", mFriend.getUserId());
                        intent.putExtra("ReplyStatus", mFriend.getReplyStatus());
                        startActivity(intent);
                    }
                }, 100);
            }
        });

    /*    if (mFriend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)
                || mFriend.getIsDevice() == 1) {// 公众号与我的手机 || 我的电脑 更多
            mMore.setVisibility(View.INVISIBLE);
        }*/

        // 加载聊天背景
        mChatBgIv = findViewById(R.id.chat_bg);
        mChatPresenter.loadBackdrop(this);
    }

    private void initBottomView() {
        mChatBottomView.setChatBottomListener(this);
        mChatBottomView.getmShotsLl().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mChatBottomView.getmShotsLl().setVisibility(View.GONE);
                String shots = PreferenceUtils.getString(mContext, Constants.SCREEN_SHOTS, "No_Shots");
                QuickSendPreviewActivity.startForResult(ChatActivity.this, shots, REQUEST_CODE_QUICK_SEND);
            }
        });
    }

    private void initContentView() {
        mChatContentView.setToUserId(mFriend.getUserId());
        mChatContentView.setData(mChatMessages);
        mChatContentView.setChatBottomView(mChatBottomView);// 需要获取多选菜单的点击事件
        mChatContentView.setMessageEventListener(this);

        mRefreshLayout = findViewById(R.id.refresh_chat_content_layout);
        mRefreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        mRefreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isSearch = false;
                mChatContentPresenter.loadContentData(false, isSearch, mSearchTime);
            }
        });
//        mChatContentView.setRefreshListener(new PullDownListView.RefreshingListener() {
//            @Override
//            public void onHeaderRefreshing() {
//                isSearch = false;
//                mChatContentPresenter.loadContentData(false,isSearch,mSearchTime);
//            }
//        });
//        // 有阅后即焚消息显示时禁止截屏，
//        mChatContentView.setOnScrollListener(new AbsListView.OnScrollListener() {
//            boolean needSecure = false;
//
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                if (view instanceof ListView) {
//                    int headerCount = ((ListView) view).getHeaderViewsCount();
//                    firstVisibleItem -= headerCount;
//                    totalItemCount -= headerCount;
//                }
//                if (firstVisibleItem < 0 || visibleItemCount <= 0) {
//                    return;
//                }
//
//                List<ChatMessage> visibleList = mChatMessages.subList(firstVisibleItem, Math.min(firstVisibleItem + visibleItemCount, totalItemCount));
//                boolean lastSecure = needSecure;
//                needSecure = false;
//                for (ChatMessage message : visibleList) {
//                    if (message.getIsReadDel()) {
//                        needSecure = true;
//                        break;
//                    }
//                }
//                if (needSecure != lastSecure) {
//                    if (needSecure) {
//                        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
//                    } else {
//                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
//                    }
//                }
//            }
//        });
    }


    /**
     * 转发&&拦截
     */
    private void instantChatMessage() {
        if (!TextUtils.isEmpty(instantMessage)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    String toUserId = getIntent().getStringExtra("fromUserId");
                    ChatMessage chatMessage = ChatMessageDao.getInstance().findMsgById(mLoginUserId, toUserId, instantMessage);
                    chatMessage.setFromUserId(mLoginUserId);
                    chatMessage.setFromUserName(mLoginNickName);
                    chatMessage.setToUserId(mFriend.getUserId());
                    chatMessage.setUpload(true);
                    chatMessage.setMySend(true);
                    chatMessage.setReSendCount(5);
                    chatMessage.setSendRead(false);
                    // 因为该消息的原主人可能开启了消息传输加密，我们对于content字段解密后存入了数据库，但是isEncrypt字段并未改变
                    // 如果我们将此消息转发给另一人，对方可能会对我方已解密的消息再次进行解密
                    chatMessage.setIsEncrypt(0);
                    chatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                    chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
                    mChatMessages.add(chatMessage);
                    mChatContentView.notifyDataSetInvalidated(true);

                    //未回复消息，即打招呼消息
                    if (mFriend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {
                        if (chatMessage.getType() == XmppMessage.TYPE_IMAGE
                                || chatMessage.getType() == XmppMessage.TYPE_VIDEO || chatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送

                            chatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                        }
                    }
                    //非好友不能发语音
                    if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM && chatMessage.getType() == XmppMessage.TYPE_VOICE) {
                        chatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                    }
                    ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, mFriend.getUserId(), chatMessage);

                    if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM
                            && mFriend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {//未回复消息，即打招呼消息
                        if (chatMessage.getType() == XmppMessage.TYPE_IMAGE
                                || chatMessage.getType() == XmppMessage.TYPE_VIDEO || chatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送
                            String content = "";
                            switch (chatMessage.getType()) {

                                case XmppMessage.TYPE_IMAGE:
                                    content = "图片发送失败，对方回复后才能使用图片功能";
                                    break;
                                case XmppMessage.TYPE_VIDEO:
                                    content = "视频发送失败，对方回复后才能使用视频功能";
                                    break;
                                case XmppMessage.TYPE_FILE:
                                    content = "文件发送失败，对方回复后才能使用文件功能";
                                    break;
                            }

                            //本地添加一个系统提示信息
                            FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, chatMessage.getToUserId(), content);

                            return;
                        } else {
                            chatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                        }
                    } else if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM
                            && mFriend.getReplyStatus() == Friend.STATUS_REPLAY_SINGLE) {//对方已经单方面发送了打招呼消息
                        chatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                    }

                    //非好友不能发送语音消息
                    if (mFriend.getStatus() != Friend.STATUS_FRIEND && mFriend.getStatus() != Friend.STATUS_SYSTEM) {
                        if (chatMessage.getType() == XmppMessage.TYPE_VOICE) {
                            String content = "互为好友才能发送语音";
                            //本地添加一个系统提示信息
                            FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, chatMessage.getToUserId(), content);

                            return;
                        }
                    }

                    coreManager.sendChatMessage(mFriend.getUserId(), chatMessage);
                    instantMessage = null;
                }
            }, 1000);
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // 忽略双指操作，避免引起莫名的问题，
        if (ev.getActionIndex() > 0) {
            return true;
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch (IllegalArgumentException ignore) {
            // 可能触发ViewPager的bug, 找不到手指头，
            // https://stackoverflow.com/a/31306753
            return true;
        }
    }

    /**
     * 返回
     */
    private void doBack() {
        if (!TextUtils.isEmpty(instantMessage)) {
            SelectionFrame selectionFrame = new SelectionFrame(this);
            selectionFrame.setSomething(null, getString(R.string.tip_forwarding_quit), new SelectionFrame.OnSelectionFrameClickListener() {
                @Override
                public void cancelClick() {
                }

                @Override
                public void confirmClick() {
                    String str = mChatBottomView.getmChatEdit().getText().toString().trim();
                    mChatBottomPresenter.saveContent(str);
                    MsgBroadcast.broadcastMsgUiUpdate(mContext);
                    finish();
                }
            });
            selectionFrame.show();
        } else {
            String str = mChatBottomView.getmChatEdit().getText().toString().trim();
            mChatBottomPresenter.saveContent(str);
            MsgBroadcast.broadcastMsgUiUpdate(mContext);
            finish();
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER,
                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!JVCideoPlayerStandardforchat.handlerBack()) {
            doBack();
        }
    }

    @Override
    protected boolean onHomeAsUp() {
        doBack();
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        instantChatMessage();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFriend = FriendDao.getInstance().getFriend(mFriend.getOwnerId(), mFriend.getUserId());
        mChatPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
        mChatContentPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
        mChatBottomPresenter.bandData(mFriend, mLoginUserId, mLoginNickName, mChatMessages);
        updateHeadAttention();

        //是否可以发语音
        if (mFriend.getRoomFlag() == 1 || mFriend.getStatus() == Friend.STATUS_FRIEND || mFriend.getStatus() == Friend.STATUS_SYSTEM) {
            mChatBottomView.updateCanSendVoice(true);
        } else {
            mChatBottomView.updateCanSendVoice(false);
        }

        //只允许关注的人发消息
        if (mIsOnlyAllowAttention && mFriend.getStatus() != Friend.STATUS_BE_ATTENTION && mFriend.getStatus() != Friend.STATUS_FRIEND) {//粉丝和好友
            mChatBottomView.isOnlyAllowAttentionSendMsg(true);
        } else {
            mChatBottomView.isOnlyAllowAttentionSendMsg(false);
        }

        //是否是好友
        if (mFriend.getStatus() == Friend.STATUS_FRIEND) {
            mChatBottomView.isFriend(true);
        } else {
            mChatBottomView.isFriend(false);
        }

        //是否被拉黑
        if (mFriend.getStatus() == Friend.STATUS_BLACKLIST || mFriend.getIsBeBlack() == 1) {//拉黑与拉黑
            mChatBottomView.updateBlack(true);
        } else {
            mChatBottomView.updateBlack(false);
        }

        // 获取[草稿]
        String draft = PreferenceUtils.getString(mContext, "WAIT_SEND" + mFriend.getUserId() + mLoginUserId, "");
        if (!TextUtils.isEmpty(draft)) {
            String s = StringUtils.replaceSpecialChar(draft);
            CharSequence content = HtmlUtils.transform200SpanString(s.replaceAll("\n", "\r\n"), true);
            mChatBottomView.getmChatEdit().setText(content);
            softKeyboardControl(true);
        }
        // 获取阅后即焚状态(因为用户可能到聊天设置界面 开启/关闭 阅后即焚，所以在onResume时需要重新获取下状态)
        isReadDel = PreferenceUtils.getInt(mContext, Constants.MESSAGE_READ_FIRE + mFriend.getUserId() + mLoginUserId, 0);
        mChatBottomPresenter.setReadDel(isReadDel);
        // 记录当前聊天对象的id
        MyApplication.IsRingId = mFriend.getUserId();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (TextUtils.isEmpty(mChatBottomView.getmChatEdit().getText().toString())) {// 清空草稿，以防消息发送出去后，通过onPause--onResume的方式给输入框赋值
            PreferenceUtils.putString(mContext, "WAIT_SEND" + mFriend.getUserId() + mLoginUserId, "");
        }
        // 将当前聊天对象id重置
        MyApplication.IsRingId = "Empty";

        VoicePlayer.instance().stop();
    }

    @Override
    protected void onDestroy() {
        ChangeBackgroundHelper.unRegistOnBackgroundChangeListener(coreManager.getSelf().getUserId() + mFriend.getUserId());
        JCVideoPlayer.releaseAllVideos();
        mChatBottomView.recordCancel();
        mChatContentView.removeVoicePlay();
        ListenerManager.getInstance().removeChatMessageListener(this);
        EventBus.getDefault().unregister(this);
        mChatPresenter.onDestroy(mContext);

        unregisterReceiver(mRefreshBroadcastReceiver);
        super.onDestroy();
    }

    /***************************************
     * ChatContentView的回调
     ***************************************/
    @Override
    public void onMyAvatarClick() {
        // 自己的头像点击
        mChatBottomView.reset();
        mChatBottomView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, mLoginUserId);
                startActivity(intent);
            }
        }, 100);
    }

    @Override
    public void onFriendAvatarClick(final String friendUserId) {
        // 好友的头像点击
        mChatBottomView.reset();
        mChatBottomView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, friendUserId);
                startActivity(intent);
            }
        }, 100);
    }

    @Override
    public void LongAvatarClick(ChatMessage chatMessage) {
    }

    @Override
    public void onNickNameClick(String friendUserId) {
    }

    @Override
    public void onMessageClick(ChatMessage chatMessage) {
    }

    @Override
    public void onMessageLongClick(ChatMessage chatMessage) {
    }

    @Override
    public void onEmptyTouch() {
        mChatBottomView.reset();
    }

    @Override
    public void onTipMessageClick(ChatMessage message) {
//        if (message.getFileSize() == XmppMessage.TYPE_83) {
//            mChatBottomPresenter.showRedReceivedDetail(message.getFilePath());
//        }
    }

    @Override
    public void onReplayClick(ChatMessage message) {
        mChatBottomPresenter.clickReplay(message);
    }

    /**
     * 点击感叹号重新发送
     */
    @Override
    public void onSendAgain(ChatMessage message) {
        mChatBottomPresenter.sendAgain(message);
    }

    /**
     * 消息撤回
     */
    @Override
    public void onMessageBack(final ChatMessage chatMessage, final int position) {
        mChatBottomPresenter.messageBack(chatMessage, position);
    }

    @Override
    public void onMessageReplay(ChatMessage chatMessage) {
        replayMessage = chatMessage;
        mChatBottomView.setReplay(chatMessage);
    }

    @Override
    public void cancelReplay() {
        replayMessage = null;
    }

    @Override
    public void onCallListener(int type) {
    }

    /***************************************
     * ChatBottomView的回调
     ***************************************/

    private void softKeyboardControl(boolean isShow) {
        // 软键盘消失
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm == null) return;
        if (isShow) {
            mChatBottomView.postDelayed(new Runnable() {
                @Override
                public void run() {// 延迟200ms在弹起，否则容易出现页面未完全加载完成软键盘弹起的效果
                    mChatBottomView.getmChatEdit().requestFocus();
                    mChatBottomView.getmChatEdit().setSelection(mChatBottomView.getmChatEdit().getText().toString().length());
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                }
            }, 200);
        } else {
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 停止播放聊天的录音
     */
    @Override
    public void stopVoicePlay() {
        VoicePlayer.instance().stop();
    }

    @Override
    public void sendAt() {
    }

    @Override
    public void sendAtMessage(String text) {
        sendText(text);// 单聊内包含@符号的消息也需要发出去
    }

    @Override
    public void sendText(String text) {
        mChatBottomPresenter.sendText(text, replayMessage);
    }

    @Override
    public void sendGif(String text) {
        mChatBottomPresenter.sendGif(text);
    }

    @Override
    public void sendCollection(String collection) {
        mChatBottomPresenter.sendCollection(collection);
    }

    @Override
    public void sendVoice(String filePath, int timeLen) {
        mChatBottomPresenter.sendVoice(filePath, timeLen);
    }

    @Override
    public void clickPhoto() {
        // 将其置为true
        /*MyApplication.GalleyNotBackGround = true;
        CameraUtil.pickImageSimple(this, REQUEST_CODE_PICK_PHOTO);*/
//        ArrayList<String> imagePaths = new ArrayList<>();
//        PhotoPickerIntent intent = new PhotoPickerIntent(ChatActivity.this);
//        intent.setSelectModel(SelectModel.MULTI);
//        // 已选中的照片地址， 用于回显选中状态
//        intent.setSelectedPaths(imagePaths);
//        startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO);
        Matisse.from(ChatActivity.this)
                .choose(MimeType.ofAll())//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(9)//可选的最大数
                .capture(false)//选择照片时，是否显示拍照
                .theme(R.style.Matisse_Dracula)
                .originalEnable(true)
                .maxOriginalSize(1024)//最大
                .captureStrategy(new CaptureStrategy(true, "com.hlg.yueliao.provider"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(REQUEST_CODE_PICK_PHOTO);

        mChatBottomView.reset();
    }

    @Override
    public void clickCamera() {
        boolean isReadContacts = PermissionUtil.checkSelfPermissions(ChatActivity.this, new String[]{Manifest.permission.CAMERA});
        if (isReadContacts) {
            openVideo();
        } else {
            PermissionUtil.requestPermissions(ChatActivity.this, 0x02, new String[]{Manifest.permission.CAMERA});
        }
    }

    private void openVideo() {
        mChatBottomView.reset();
        Intent intent = new Intent(this, VideoRecorderActivity.class);
        startActivity(intent);
    }

    @Override
    public void clickStartRecord() {
        // 现拍照录像ui和二为一，统一在clickCamera内处理
       /* Intent intent = new Intent(this, VideoRecorderActivity.class);
        startActivity(intent);*/
    }

    @Override
    public void clickLocalVideo() {
        // 现拍照录像ui和二为一，统一在clickCamera内处理
        /*Intent intent = new Intent(this, LocalVideoActivity.class);
        intent.putExtra(AppConstant.EXTRA_ACTION, AppConstant.ACTION_SELECT);
        intent.putExtra(AppConstant.EXTRA_MULTI_SELECT, true);
        startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);*/
    }

    @Override
    public void clickAudio() {
    }

    @Override
    public void clickVideoChat() {
    }

    @Override
    public void clickFile() {
        //跳转选择文件界面
        navigateToAddMucFileActivity();
    }

    private void navigateToAddMucFileActivity() {
        Intent intent = new Intent(mContext, AddMucFileActivity2.class);
        intent.putExtra(SELECT_FILES, true);
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }


    @Override
    public void clickContact() {
        SendContactsActivity.start(this, REQUEST_CODE_SEND_CONTACT);
    }

    @Override
    public void clickLocation() {
        Intent intent = new Intent(this, MapPickerActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT_Locate);
    }

    @Override
    public void clickCard() {
        Intent intent = new Intent(this, TabSelectContactsActivity.class);
        intent.putExtra("SendCard", true);
        intent.putExtra("isRoom", false);
        startActivityForResult(intent, REQUEST_CODE_SEND_CARD);
//        SelectCardPopupWindow mSelectCardPopupWindow = new SelectCardPopupWindow(this, this);
//        mSelectCardPopupWindow.showAtLocation(findViewById(R.id.root_view),
//                Gravity.CENTER, 0, 0);
    }


    /**
     * @author: czl
     * @description 点击发红包
     * @date: 2019/10/9 11:18
     */
    @Override
    public void clickRedpacket() {
        //获取最新的关系
        mFriend = FriendDao.getInstance().getFriend(mFriend.getOwnerId(), mFriend.getUserId());
        //如果不是好友关系
        if (mFriend.getStatus() != Friend.STATUS_FRIEND) {
            ToastUtil.showToast(mContext, "只有好友关系才能发红包");
            return;
        }
        isBindAlipay();
    }

    /**
     * @author: czl
     * @description 是否绑定支付宝
     * @date: 2019/10/9 11:10
     */
    public void isBindAlipay() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        HttpUtils.post().url(coreManager.getConfig().IS_BIND_ALIPAY)
                .params(params)
                .build()
                .execute(new BaseCallback<IsBindAlipayBean>(IsBindAlipayBean.class) {
                    @Override
                    public void onResponse(ObjectResult<IsBindAlipayBean> result) {
                        DialogHelper.
                                dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            IsBindAlipayBean mIsBindAlipayBean = result.getData();
                            if (mIsBindAlipayBean.getState().equals("BINDING")) {//已绑定支付宝 跳转发红包页面
                                Intent intent = new Intent(ChatActivity.this, SendRedPacketActivity1.class).putExtra("toUserId", mFriend.getUserId());
                                startActivityForResult(intent, REQUEST_CODE_SEND_RED);
                            } else {//没绑定支付宝 跳转至绑定支付宝页面
                                startActivity(new Intent(ChatActivity.this, IdentityAuthenticationActivity.class)
                                        .putExtra("aliPayNickName", "").putExtra("isRedpacket", true));
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showToast(ChatActivity.this, e.toString());
                        Log.e("AlipayAutoMsg", "Exception", e);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(String str) {
        //绑定支付宝成功 直接跳转发红包页面
        if (str.equals("bind_success")) {
            Intent intent = new Intent(ChatActivity.this, SendRedPacketActivity1.class).putExtra("toUserId", mFriend.getUserId());
            startActivityForResult(intent, REQUEST_CODE_SEND_RED);
        }
    }

    @Override
    public void clickTransferMoney() {
        Intent intent = new Intent(this, TransferMoneyActivity.class);
        intent.putExtra(AppConstant.EXTRA_USER_ID, mFriend.getUserId());
        intent.putExtra(AppConstant.EXTRA_NICK_NAME, TextUtils.isEmpty(mFriend.getRemarkName()) ? mFriend.getNickName() : mFriend.getRemarkName());
        startActivity(intent);
    }

    @Override
    public void clickCollection() {
        Intent intent = new Intent(this, SelectCollectionActivity.class);

        startActivityForResult(intent, REQUEST_CODE_SEND_COLLECTION);
    }


    @Override
    public void clickShake() {
        mChatBottomPresenter.clickShake();
    }

    /**
     * 戳一戳动画
     *
     * @param type 动画类型
     */
    private void shakeAnimation(int type) {
        Animation shake;
        if (type == 0) {
            shake = AnimationUtils.loadAnimation(this, R.anim.shake_from);
        } else {
            shake = AnimationUtils.loadAnimation(this, R.anim.shake_to);
        }
        mChatContentView.startAnimation(shake);
        mChatBottomView.startAnimation(shake);
        mChatBgIv.startAnimation(shake);
    }

    /**
     * 得到选中的名片
     */
    @Override
    public void sendCardS(List<Friend> friends) {
        for (int i = 0; i < friends.size(); i++) {
            mChatBottomPresenter.sendCard(friends.get(i));
        }
    }

    @Override
    public void onInputState() {
        // 获得输入状态
        PrivacySetting privacySetting = PrivacySettingHelper.getPrivacySettings(this);
        boolean input = privacySetting.getIsTyping() == 1;
        if (input && coreManager.isLogin()) {
            ChatMessage message = new ChatMessage();
            // 正在输入消息
            message.setType(XmppMessage.TYPE_INPUT);
            message.setFromUserId(mLoginUserId);
            message.setFromUserName(mLoginNickName);
            message.setToUserId(mFriend.getUserId());
            message.setTimeSend(TimeUtils.sk_time_current_time());
            message.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
            coreManager.sendChatMessage(mFriend.getUserId(), message);
        }
    }

    /**
     * 新消息到来
     */
    @Override
    public boolean onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        if (isGroupMsg) {
            return false;
        }

        //被关注更新关系消息
        if (message.getType() == XmppMessage.TYPE_SEND_ATTENTION_NOTICE || message.getType() == XmppMessage.TYPE_SEND_FRIEND_NOTICE) {
            updateFriendStatus(message.getType() == XmppMessage.TYPE_SEND_ATTENTION_NOTICE ? Friend.STATUS_BE_ATTENTION : Friend.STATUS_FRIEND);
            return false;
        }

        if (message.getType() == XmppMessage.TYPE_REPLY_STATUS) {//陌生人回复提醒
            if (message.getFromUserId().equals(mFriend.getUserId())) {
                mFriend = FriendDao.getInstance().getFriend(mFriend.getOwnerId(), mFriend.getUserId());
                mChatPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
                mChatContentPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
                mChatBottomPresenter.bandData(mFriend, mLoginUserId, mLoginNickName, mChatMessages);
                //是否可以发语音
                if (mFriend.getRoomFlag() == 1 || mFriend.getStatus() == Friend.STATUS_FRIEND || mFriend.getStatus() == Friend.STATUS_SYSTEM) {
                    mChatBottomView.updateCanSendVoice(true);
                } else {
                    mChatBottomView.updateCanSendVoice(false);
                }

            }
            return false;
        }

        /**
         *  因为重发机制，当对方处于弱网时，不能及时接收我方的消息回执而给我方发送了两条甚至多条一样的消息
         *  而我方则会收到两条甚至多条一样的消息存入数据库(数据库已去重)，如果我正好处于消息发送方的聊天界面
         *  则会回调多次onNewMessage方法，而该方法内又没做去重，所以会出现显示两条一模一样的消息，退出当前界面在进入
         *  该界面又只有一条的问题
         *
         */
        if (mChatMessages.size() > 1) {
            if (mChatMessages.get(mChatMessages.size() - 1).getPacketId().equals(message.getPacketId())) {// 最后一条消息的msgId==新消息的msgId
                Log.e("zq", "收到一条重复消息");
                return false;
            }
        }

        if (mFriend.getIsDevice() == 1) {// 当前界面为我的设备界面 如果收到其他设备的转发消息，也会通知过来
            ChatMessage chatMessage = ChatMessageDao.getInstance().
                    findMsgById(mLoginUserId, mFriend.getUserId(), message.getPacketId());
            if (chatMessage == null) {
                return false;
            }
        }

        /*
         现在需要支持多点登录，此刻该条消息为我另外一台设备发送的消息，我需要将该条消息存入对应的数据库并更新界面来达到同步
         */
        if (fromUserId.equals(mLoginUserId)
                && !TextUtils.isEmpty(message.getToUserId())
                && message.getToUserId().equals(mFriend.getUserId())) {// 收到自己转发的消息且该条消息为发送给当前聊天界面的
            message.setMySend(true);
            message.setMessageState(MESSAGE_SEND_SUCCESS);
            mChatMessages.add(message);
            if (mChatContentView.shouldScrollToBottom()) {
                mChatContentView.notifyDataSetInvalidated(true);
            } else {
                mChatContentView.notifyDataSetChanged();
            }
            if (message.getType() == XmppMessage.TYPE_SHAKE) {// 戳一戳
                shakeAnimation(1);
            }
            return true;
        }

        if (mFriend.getUserId().compareToIgnoreCase(fromUserId) == 0) {// 是该人的聊天消息
            mChatMessages.add(message);
            if (mChatContentView.shouldScrollToBottom()) {
                mChatContentView.notifyDataSetInvalidated(true);
            } else {
                mChatContentView.notifyDataSetChanged();
            }
            if (message.getType() == XmppMessage.TYPE_SHAKE) {// 戳一戳
                shakeAnimation(1);
            }
            return true;
        }
        return false;
    }

    private void updateFriendStatus(int status) {
        mFriend.setStatus(status);
        //是否可以发语音
        if (mFriend.getRoomFlag() == 1 || mFriend.getStatus() == Friend.STATUS_FRIEND || mFriend.getStatus() == Friend.STATUS_SYSTEM) {
            mChatBottomView.updateCanSendVoice(true);
        } else {
            mChatBottomView.updateCanSendVoice(false);
        }
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {
        Log.e("zq", messageState + "，" + msgId);
        if (TextUtils.isEmpty(msgId)) {
            return;
        }

        //对方尚未回复你，你只能发送10条信息
        if (messageState == ChatMessageListener.MESSAGE_SEND_OVER) {
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(XmppMessage.TYPE_TIP);
            chatMessage.setFromUserId(mLoginUserId);
            chatMessage.setContent("对方尚未回复你，你只能发送10条信息");
            chatMessage.setMessageState(messageState);
            chatMessage.setMySend(false);// 表示不是自己发的
            chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));// 随机产生一个PacketId
            chatMessage.setTimeSend(TimeUtils.sk_time_current_time());
            mChatMessages.add(chatMessage);
        }

        for (int i = 1; i < mChatMessages.size(); i++) {
            ChatMessage msg = mChatMessages.get(i);
            if (msgId.equals(msg.getPacketId())) {
                /**
                 * 之前发现对方已经收到消息了，这里还在转圈，退出重进之后又变为送达了，
                 * 调试时发现出现该问题是因为消息状态先更新的1，在更新的0，这里处理下
                 */
                if (messageState == 0) {
                    return;
                }
                msg.setMessageState(messageState);
                mChatContentView.notifyDataSetInvalidated(mChatMessages.size() - 1);
                break;
            }
        }
    }

    /**
     * 复制自com.sk.weichat.ui.me.LocalVideoActivity#helloEventBus(com.sk.weichat.adapter.MessageVideoFile)
     * 主要是CameraDemoActivity录制结束不走activity result, 而是发EventBus,
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventUploadFileRate message) {
        for (int i = 1; i < mChatMessages.size(); i++) {
            if (mChatMessages.get(i).getPacketId().equals(message.getPacketId())) {
                mChatMessages.get(i).setUploadSchedule(message.getRate());
                mChatMessages.get(i).setUpload(message.getRate() == 100);
                mChatContentView.notifyDataSetChanged();
                break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventUploadCancel message) {
        for (int i = 1; i < mChatMessages.size(); i++) {
            if (mChatMessages.get(i).getPacketId().equals(message.getPacketId())) {
                mChatMessages.remove(i);
                mChatContentView.notifyDataSetChanged();
                ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId, mFriend.getUserId(), message.getPacketId());
                break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageVideoFile message) {
        VideoFile videoFile = new VideoFile();
        videoFile.setCreateTime(TimeUtils.f_long_2_str(System.currentTimeMillis()));
        videoFile.setFileLength(message.timelen);
        videoFile.setFileSize(message.length);
        videoFile.setFilePath(message.path);
        videoFile.setOwnerId(coreManager.getSelf().getUserId());
        VideoFileDao.getInstance().addVideoFile(videoFile);
        String filePath = message.path;
        if (TextUtils.isEmpty(filePath)) {
            ToastUtil.showToast(this, R.string.record_failed);
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            ToastUtil.showToast(this, R.string.record_failed);
            return;
        }
        mChatBottomPresenter.sendVideo(file);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageLocalVideoFile message) {
        mChatBottomPresenter.sendVideo(message.file);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(EventRedReceived message) {
        mChatBottomPresenter.showReceiverRedLocal(message.getOpenRedpacket());
    }

    /**
     * @author: czl
     * @description 红包消息状态
     * @date: 2019/10/11 15:12
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(EventRedReceivedStatus message) {
        //更新本地红包消息状态
        ChatMessageDao.getInstance().updateChatRedpacketMessageRStatus(mLoginUserId, mFriend.getUserId(), message.getMessgae_id(), message.getStatus());
        for (int i = 1; i < mChatMessages.size(); i++) {
            ChatMessage msg = mChatMessages.get(i);
            if (message.getMessgae_id().equals(msg.getPacketId())) {
                msg.setFileSize(message.getStatus());
                updateContent(false);
//                mChatContentView.notifyDataSetInvalidated(mChatMessages.size() - 1);
                break;
            }
        }
    }

    /*******************************************
     * 接收到EventBus后的后续操作
     ******************************************/
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEventRequert message) {
        requstImageText(message.url);
    }

    private void requstImageText(String url) {
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("TAG", response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
                ToastUtil.showToast(mContext, error.getMessage());
            }
        });
        // TODO: 2019/6/14
        MyApplication.getInstance().getFastVolley().addDefaultRequest(null, stringRequest);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEventGpu message) {// 拍照返回
        mChatBottomPresenter.photograph(new File(message.event));
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventTransfer message) {
        mChatContentView.postDelayed(() -> {
            if (message.getChatMessage().getType() == XmppMessage.TYPE_TRANSFER) {// 发送转账消息
                mChatMessages.add(message.getChatMessage());
                mChatContentView.notifyDataSetInvalidated(true);
                mChatBottomPresenter.sendMessage(message.getChatMessage());
            } else {// 重发转账消息 || 确认领取
                for (int i = 1; i < mChatMessages.size(); i++) {
                    if (TextUtils.equals(mChatMessages.get(i).getPacketId(),
                            message.getChatMessage().getPacketId())) {
                        if (message.getChatMessage().getType() == TransferMoneyDetailActivity.EVENT_REISSUE_TRANSFER) {
                            ChatMessage chatMessage = mChatMessages.get(i).clone(false);
                            mChatMessages.add(chatMessage);
                            mChatContentView.notifyDataSetInvalidated(true);
                            mChatBottomPresenter.sendMessage(chatMessage);
                        } else {
                            mChatMessages.get(i).setFileSize(2);
                            ChatMessageDao.getInstance().updateChatMessageReceiptStatus(mLoginUserId, mFriend.getUserId(), message.getChatMessage().getPacketId());
                            mChatContentView.notifyDataSetChanged();
                        }
                    }
                }
            }
        }, 50);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEvent message) {
        Log.e("xuan", "helloEventBus  MessageEvent: " + message.message);
        if (mDelayDelMaps == null || mDelayDelMaps.isEmpty() || mChatMessages == null || mChatMessages.size() == 0) {
            return;
        }

        for (ChatMessage chatMessage : mChatMessages) {
            if (chatMessage.getFilePath().equals(message.message) && mDelayDelMaps.contains(chatMessage.getPacketId())) {
                String packedId = chatMessage.getPacketId();

                if (ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId, mFriend.getUserId(), packedId)) {
                    Log.e("xuan", "删除成功 ");
                } else {
                    Log.e("xuan", "删除失败 " + packedId);
                }
                mDelayDelMaps.remove(packedId);
                mChatContentView.removeItemMessage(packedId);

                break;
            }
        }

    }

    // 阅后即焚的处理
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEventClickFire message) {
        Log.e("xuan", "helloEventBus: " + message.event + " ,  " + message.packedId);

        if ("delete".equals(message.event)) {
            mDelayDelMaps.remove(message.packedId);
            ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId, mFriend.getUserId(), message.packedId);
            mChatContentView.removeItemMessage(message.packedId);
        } else if ("delay".equals(message.event)) {
            mDelayDelMaps.add(message.packedId);
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageEventClickable message) {
        if (message.event.isMySend()) {
            shakeAnimation(0);
        } else {
            shakeAnimation(1);
        }
    }

    // 发送多选消息
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventMoreSelected message) {
        List<ChatMessage> mSelectedMessageList = new ArrayList<>();
        if (message.getToUserId().equals("MoreSelectedCollection") || message.getToUserId().equals("MoreSelectedEmail")) {// 多选 收藏 || 保存
            moreSelected(false, 0);
            return;
        }
        if (message.getToUserId().equals("MoreSelectedDelete")) {// 多选 删除
            for (int i = 1; i < mChatMessages.size(); i++) {
                if (mChatMessages.get(i).isMoreSelected) {
                    if (ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId, mFriend.getUserId(), mChatMessages.get(i))) {
                        Log.e("more_selected", "删除成功");
                    } else {
                        Log.e("more_selected", "删除失败");
                    }
                    mSelectedMessageList.add(mChatMessages.get(i));
                }
            }

            String mMsgIdListStr = "";
            for (int i = 0; i < mSelectedMessageList.size(); i++) {
                if (i == mSelectedMessageList.size() - 1) {
                    mMsgIdListStr += mSelectedMessageList.get(i).getPacketId();
                } else {
                    mMsgIdListStr += mSelectedMessageList.get(i).getPacketId() + ",";
                }
            }

            mChatPresenter.deleteMessage(mMsgIdListStr);// 服务端也需要删除
            mChatMessages.removeAll(mSelectedMessageList);
        } else {// 多选 转发
            if (message.isSingleOrMerge()) {// 合并转发
                List<String> mStringHistory = new ArrayList<>();
                for (int i = 1; i < mChatMessages.size(); i++) {
                    if (mChatMessages.get(i).isMoreSelected) {
                        String body = mChatMessages.get(i).toJsonString();
                        mStringHistory.add(body);
                    }
                }
                String detail = JSON.toJSONString(mStringHistory);
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setType(XmppMessage.TYPE_CHAT_HISTORY);
                chatMessage.setFromUserId(mLoginUserId);
                chatMessage.setFromUserName(mLoginNickName);
                chatMessage.setToUserId(message.getToUserId());
                chatMessage.setContent(detail);
                chatMessage.setMySend(true);
                chatMessage.setReSendCount(0);
                chatMessage.setSendRead(false);
                chatMessage.setIsEncrypt(0);
                chatMessage.setIsReadDel(0);
                String s = TextUtils.isEmpty(mFriend.getRemarkName()) ? mFriend.getNickName() : mFriend.getRemarkName();
                chatMessage.setObjectId(getString(R.string.chat_history_place_holder, s, mLoginNickName));
                chatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));

                ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, message.getToUserId(), chatMessage);

                if (message.getToUserId().equals(mFriend.getUserId())) {// 转发给当前对象
                    mChatMessages.add(chatMessage);
                }
                if (message.isGroupMsg()) {
                    coreManager.sendMucChatMessage(message.getToUserId(), chatMessage);
                } else {
                    coreManager.sendChatMessage(message.getToUserId(), chatMessage);
                }

            } else {// 逐条转发
                for (int i = 1; i < mChatMessages.size(); i++) {
                    if (mChatMessages.get(i).isMoreSelected) {
                        ChatMessage chatMessage = ChatMessageDao.getInstance().findMsgById(mLoginUserId, mFriend.getUserId(), mChatMessages.get(i).getPacketId());
                        if (chatMessage.getType() == XmppMessage.TYPE_RED) {
                            chatMessage.setType(XmppMessage.TYPE_TEXT);
                            chatMessage.setContent(getString(R.string.msg_red_packet));
                        } else if (chatMessage.getType() >= XmppMessage.TYPE_IS_CONNECT_VOICE
                                && chatMessage.getType() <= XmppMessage.TYPE_EXIT_VOICE) {
                            chatMessage.setType(XmppMessage.TYPE_TEXT);
                            chatMessage.setContent(getString(R.string.msg_video_voice));
                        } else if (chatMessage.getType() == XmppMessage.TYPE_SHAKE) {
                            chatMessage.setType(XmppMessage.TYPE_TEXT);
                            chatMessage.setContent(getString(R.string.msg_shake));
                        }
                        chatMessage.setFromUserId(mLoginUserId);
                        chatMessage.setFromUserName(mLoginNickName);
                        chatMessage.setToUserId(message.getToUserId());
                        chatMessage.setUpload(true);
                        chatMessage.setMySend(true);
                        chatMessage.setReSendCount(0);
                        chatMessage.setSendRead(false);
                        chatMessage.setIsEncrypt(0);
                        chatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                        chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
                        mSelectedMessageList.add(chatMessage);
                    }
                }

                Friend toFriend = FriendDao.getInstance().getFriend(mLoginUserId, message.getToUserId());
                for (int i = 0; i < mSelectedMessageList.size(); i++) {

                    //未回复消息，即打招呼消息
                    if (toFriend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {
                        if (mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_IMAGE
                                || mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_VIDEO || mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送

                            mSelectedMessageList.get(i).setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                        }
                    }
                    //非好友不能发语音
                    if (toFriend.getStatus() != Friend.STATUS_FRIEND && toFriend.getStatus() != Friend.STATUS_SYSTEM && mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_VOICE) {
                        mSelectedMessageList.get(i).setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                    }
                    ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, message.getToUserId(), mSelectedMessageList.get(i));

                    if (toFriend.getStatus() != Friend.STATUS_FRIEND && toFriend.getStatus() != Friend.STATUS_SYSTEM
                            && toFriend.getReplyStatus() == Friend.STATUS_REPLAY_NONE) {//未回复消息，即打招呼消息
                        if (mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_IMAGE
                                || mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_VIDEO || mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送
                            String content = "";
                            switch (mSelectedMessageList.get(i).getType()) {

                                case XmppMessage.TYPE_IMAGE:
                                    content = "图片发送失败，对方回复后才能使用图片功能";
                                    break;
                                case XmppMessage.TYPE_VIDEO:
                                    content = "视频发送失败，对方回复后才能使用视频功能";
                                    break;
                                case XmppMessage.TYPE_FILE:
                                    content = "文件发送失败，对方回复后才能使用文件功能";
                                    break;
                            }

                            //本地添加一个系统提示信息
                            FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, message.getToUserId(), content);
                            moreSelected(false, 0);
                            return;
                        } else {
                            mSelectedMessageList.get(i).setMsgType(ChatMessage.TYPE_HELLO);
                        }
                    } else if (toFriend.getStatus() != Friend.STATUS_FRIEND && toFriend.getStatus() != Friend.STATUS_SYSTEM
                            && toFriend.getReplyStatus() == Friend.STATUS_REPLAY_SINGLE) {//对方已经单方面发送了打招呼消息
                        mSelectedMessageList.get(i).setMsgType(ChatMessage.TYPE_HELLO);
                    }

                    //非好友不能发送语音消息
                    if (toFriend.getStatus() != Friend.STATUS_FRIEND && toFriend.getStatus() != Friend.STATUS_SYSTEM) {
                        if (mSelectedMessageList.get(i).getType() == XmppMessage.TYPE_VOICE) {
                            String content = "互为好友才能发送语音";
                            //本地添加一个系统提示信息
                            FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, message.getToUserId(), content);
                            moreSelected(false, 0);
                            return;
                        }
                    }
                    if (message.isGroupMsg()) {
                        coreManager.sendMucChatMessage(message.getToUserId(), mSelectedMessageList.get(i));
                    } else {
                        coreManager.sendChatMessage(message.getToUserId(), mSelectedMessageList.get(i));
                    }
                    if (message.getToUserId().equals(mFriend.getUserId())) {// 转发给当前对象
                        mChatMessages.add(mSelectedMessageList.get(i));
                    }
                }
            }
        }
        moreSelected(false, 0);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final MessageUploadChatRecord message) {
        final CreateCourseDialog dialog = new CreateCourseDialog(this, new CreateCourseDialog.CoureseDialogConfirmListener() {
            @Override
            public void onClick(String content) {
                mChatBottomPresenter.upLoadChatList(message.chatIds, content);
            }
        });
        dialog.show();
    }

    /**
     * 被移出黑名单通知
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventChatRemoveBlack message) {
        if (message.getUserId().equals(mFriend.getUserId())) {
            mFriend = FriendDao.getInstance().getFriend(mLoginUserId, mFriend.getUserId());// 重新获取friend对象
            mChatPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
            mChatContentPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
            mChatBottomPresenter.bandData(mFriend, mLoginUserId, mLoginNickName, mChatMessages);

            if (mFriend.getStatus() == Friend.STATUS_BLACKLIST || mFriend.getIsBeBlack() == 1) {//拉黑与拉黑
                mChatBottomView.updateBlack(true);
            } else {
                mChatBottomView.updateBlack(false);
            }

            if (mIsOnlyAllowAttention && mFriend.getStatus() != Friend.STATUS_BE_ATTENTION && mFriend.getStatus() != Friend.STATUS_FRIEND) {//粉丝和好友
                mChatBottomView.isOnlyAllowAttentionSendMsg(true);
            } else {
                mChatBottomView.isOnlyAllowAttentionSendMsg(false);
            }

        }
    }

    /**
     * 拉黑、被拉黑、被取消关注、被关注、加好友改变“只允许我关注的人发消息”状态
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final EventChatAllowSendMsg message) {
        if (message.getUserId().equals(mFriend.getUserId())) {
            mFriend = FriendDao.getInstance().getFriend(mLoginUserId, mFriend.getUserId());// 重新获取friend对象
            mChatPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
            mChatContentPresenter.bandData(mFriend, mLoginUserId, mChatMessages);
            mChatBottomPresenter.bandData(mFriend, mLoginUserId, mLoginNickName, mChatMessages);

            if (mFriend.getStatus() == Friend.STATUS_BLACKLIST || mFriend.getIsBeBlack() == 1) {//拉黑与拉黑
                mChatBottomView.updateBlack(true);
            } else {
                mChatBottomView.updateBlack(false);
            }

            if (mIsOnlyAllowAttention && mFriend.getStatus() != Friend.STATUS_BE_ATTENTION && mFriend.getStatus() != Friend.STATUS_FRIEND) {//粉丝和好友
                mChatBottomView.isOnlyAllowAttentionSendMsg(true);
            } else {
                mChatBottomView.isOnlyAllowAttentionSendMsg(false);
            }

        }
    }

    /**
     * 个人信息页关注成为好友发消息时更新
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(final ChatMessage message) {
        if (message.getToUserId().equals(mFriend.getUserId())) {
            mChatMessages.add(message);
            mChatContentView.notifyDataSetInvalidated(mChatMessages.size() - 1);
        }

    }


    @Override
    public void updateContent(boolean b) {
        mChatContentView.notifyDataSetInvalidated(b);
    }

    @Override
    public void updateContent(int position) {
        mChatContentView.notifyDataSetInvalidated(position);
    }

    @Override
    public void updateOnLineDescribe(String describe) {
        mTvOnline.setText(describe);
    }

    @Override
    public void changeOnLineState(boolean state) {
        if (state) {
            mTvOnline.setVisibility(View.VISIBLE);
        } else {
            mTvOnline.setVisibility(View.GONE);
        }
    }

    @Override
    public void changeChannelName(Friend friend) {
        mFriend = friend;
        String s = mTvTitle.getText().toString();
        if (s.contains(InternationalizationHelper.getString("JX_OnLine"))) {
            mTvTitle.setText(TextUtils.isEmpty(mFriend.getRemarkName()) ? mFriend.getNickName() : mFriend.getRemarkName());
        } else {
            mTvTitle.setText(TextUtils.isEmpty(mFriend.getRemarkName()) ? mFriend.getNickName() : mFriend.getRemarkName());
        }
    }

    @Override
    public void showToastMsg(String msg) {
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void moreSelected(boolean isShow, int position) {
        {
            mChatBottomView.showMoreSelectMenu(isShow);
            if (isShow) {
                findViewById(R.id.iv_title_left).setVisibility(View.GONE);
                findViewById(R.id.tv_num_left).setVisibility(View.GONE);
                findViewById(R.id.iv_title_right).setVisibility(View.GONE);
                mTvTitleLeft.setVisibility(View.VISIBLE);
                if (!mChatMessages.get(position).getIsReadDel()) {// 非阅后即焚消息才能被选中
                    mChatMessages.get(position).setMoreSelected(true);
                }
            } else {
                findViewById(R.id.iv_title_left).setVisibility(View.VISIBLE);
                findViewById(R.id.iv_title_right).setVisibility(View.VISIBLE);
                TextView tvNum = findViewById(R.id.tv_num_left);
                if (!TextUtils.isEmpty(tvNum.getText().toString())) {
                    findViewById(R.id.tv_num_left).setVisibility(View.VISIBLE);
                }

                mTvTitleLeft.setVisibility(View.GONE);
                for (int i = 1; i < mChatMessages.size(); i++) {
                    mChatMessages.get(i).setMoreSelected(false);
                }
            }
            mChatContentView.setIsShowMoreSelect(isShow);
            mChatContentView.notifyDataSetChanged();
        }
    }

    /**
     * 更换聊天背景
     *
     * @param obj 背景图
     */
    @Override
    public void changeBackdrop(Object obj) {
        if (obj == null) {
            mChatBgIv.setImageDrawable(null);
        } else if (obj instanceof GifDrawable) {
            mChatBgIv.setImageDrawable((GifDrawable) obj);
        } else if (obj instanceof File) {
            Glide.with(ChatActivity.this)
                    .load((File) obj)
                    .error(R.drawable.fez)
                    .into(mChatBgIv);
        } else if (obj instanceof String) {
            Glide.with(ChatActivity.this)
                    .load((String) obj)
                    .error(R.drawable.fez)
                    .into(mChatBgIv);
        }

    }

    /**
     * 重发信息
     */
    @Override
    public void onSendMessageReplay() {
        replayMessage = null;
        mChatBottomView.resetReplay();
    }

    /**
     * 红包弹框
     *
     * @param message
     */
    @Override
    public void showRedDialog(ChatMessage message) {
        RedDialogBean redDialogBean = new RedDialogBean(message.getFromUserId(), message.getFromUserName(), message.getContent(), null);
        mRedDialog = new RedDialog(mContext, redDialogBean, () -> {
            // 打开红包
            mChatBottomPresenter.openRedPacket(message);
        });
        mRedDialog.show();
    }

    /**
     * 关闭红包弹框
     */
    @Override
    public void closeRedDialog() {
        if (mRedDialog != null) {
            mRedDialog.dismiss();
        }
    }

    /**
     * 戳一戳
     *
     * @param type
     */
    @Override
    public void onShake(int type) {
        shakeAnimation(type);
    }

    /**
     * 公众号菜单
     *
     * @param publicMenusList
     */
    @Override
    public void fillRoomMenu(List<PublicMenu> publicMenusList) {
        //mChatBottomView.fillRoomMenu(publicMenusList);
    }

    /**
     * 数据刷新完成回调
     *
     * @param hasMoreDate
     */
    @Override
    public void onHeaderRefreshingCompleted(boolean hasMoreDate) {
        mRefreshLayout.finishRefresh();
        if (!hasMoreDate) {
            mRefreshLayout.setEnableRefresh(true);
            mRefreshLayout.setEnableLoadMore(true);
            mRefreshLayout.setEnablePureScrollMode(true);
        } else {
            mRefreshLayout.setEnablePureScrollMode(false);
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.setEnableRefresh(true);
        }
    }

    /**
     * @author: czl
     * @description 是否只允许我关注的人发消息
     * @date: 2019/9/21 10:40
     */
    @Override
    public void onlyAllowAttentionSendMsg(boolean hasMoreDate) {
        mIsOnlyAllowAttention = hasMoreDate;
        //如果 该好友不是我的好友或者粉丝  则判断对方是否开启了“只允许我关注的人发消息”功能
        if (mIsOnlyAllowAttention && mFriend.getStatus() != Friend.STATUS_BE_ATTENTION && mFriend.getStatus() != Friend.STATUS_FRIEND) {//粉丝和好友
            mChatBottomView.isOnlyAllowAttentionSendMsg(hasMoreDate);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_FILE:
                    //
                    ArrayList<String> filePaths = data.getStringArrayListExtra(SELECT_FILES);
                    if (filePaths != null) {
                        for (int i = 0; i < filePaths.size(); i++) {
                            mChatBottomPresenter.sendFile(new File(filePaths.get(i)));
                        }
                    }
                    // 系统管理器返回文件
//                    String file_path = FileUtils.getPath(ChatActivity.this, data.getData());
//                    Log.e("xuan", "conversionFile: " + file_path);
//                    if (file_path == null) {
//                        ToastUtil.showToast(mContext, R.string.tip_file_not_supported);
//                    } else {
//                        mChatBottomPresenter.sendFile(new File(file_path));
//                    }
                    break;
                case REQUEST_CODE_CAPTURE_PHOTO:
                    // 拍照返回
                    if (mNewPhotoUri != null) {
                        mChatBottomPresenter.photograph(new File(mNewPhotoUri.getPath()));
                    }
                    break;
                case REQUEST_CODE_PICK_PHOTO:
                    if (data != null) {
                        //boolean isOriginal = data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);

                        List<String> result = Matisse.obtainPathResult(data);
                        mChatBottomPresenter.sendPhoneAndVidio(result);
                        //mChatBottomPresenter.album(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), isOriginal);
                    } else {
                        ToastUtil.showToast(this, R.string.c_photo_album_failed);
                    }
                    break;
                case REQUEST_CODE_SELECT_VIDEO: {
                    // 选择视频的返回
                    mChatBottomPresenter.clickVideo(data);
                    break;
                }
                case REQUEST_CODE_SELECT_Locate: // 选择位置的返回
                    mChatBottomPresenter.clickLocate(data);
                    break;
                case REQUEST_CODE_SEND_COLLECTION: {
                    List<CollectionEvery> list = data.getParcelableArrayListExtra(SelectCollectionKey);
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            mChatBottomPresenter.clickCollectionSend(list.get(i), replayMessage);
                        }
                    } else {

                    }


//                    String json = data.getStringExtra("data");
//                    CollectionEvery collection = JSON.parseObject(json, CollectionEvery.class);
//                    mChatBottomPresenter.clickCollectionSend(collection, replayMessage);
                    break;
                }
                case REQUEST_CODE_QUICK_SEND:
                    String image = QuickSendPreviewActivity.parseResult(data);
                    mChatBottomPresenter.sendImage(new File(image));
                    break;
                case REQUEST_CODE_SEND_CARD:
                    List<Friend> Friends = (List<Friend>) data.getSerializableExtra("FriendCardList");
                    sendCardS(Friends);
                    break;
                case REQUEST_CODE_SEND_CONTACT: {
                    List<Contacts> contactsList = SendContactsActivity.parseResult(data);
                    if (contactsList == null) {
                        ToastUtil.showToast(mContext, R.string.simple_data_error);
                    } else {
                        mChatBottomPresenter.sendContacts(contactsList, replayMessage);
                    }
                    break;
                }

                default:
                    super.onActivityResult(requestCode, resultCode, data);
            }
        } else if (requestCode == REQUEST_MICROPHONE_CODE) {
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(ChatActivity.this, new String[]{Manifest.permission.RECORD_AUDIO});
            if (isReadContacts) {
                mChatBottomView.showVoiceBtn();
            }
        } else if (requestCode == REQUEST_CAMERA_CODE) {
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(ChatActivity.this, new String[]{Manifest.permission.CAMERA});
            if (isReadContacts) {
                openVideo();
            }
        } else if (requestCode == REQUEST_CODE_SEND_RED) { //支付宝发送红包成功
            if (data != null && data.getExtras() != null) {
                Bundle bundle = data.getExtras();
                String messageId = bundle.getString("messageId");//消息id
                //查询本地消息
                ChatMessage message = ChatMessageDao.getInstance().findMsgById(mLoginUserId, mFriend.getUserId(), messageId);
                mChatMessages.add(message);
                updateContent(true);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        if (isAllGranted) {// 请求权限返回 已全部授权
            if (requestCode == 0x01) {//录音权限
                mChatBottomView.showVoiceBtn();
            } else {//拍照权限
                openVideo();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
        String tips = "";
        if (perms.get(0).endsWith("android.permission.RECORD_AUDIO")) {
            tips = getString(R.string.permission_microphone);
        } else if (perms.get(0).endsWith("android.permission.CAMERA")) {
            tips = getString(R.string.permission_photo);
        }
        if (onceAgain) {
            TipDialog mTipDialog = new TipDialog(this);
            mTipDialog.setmConfirmOnClickListener(getString(R.string.tip_reject_permission_place_holder, tips), new TipDialog.ConfirmOnClickListener() {
                @Override
                public void confirm() {
                    if (requestCode == 0x01) {//录音权限
                        PermissionUtil.startApplicationDetailsSettings(ChatActivity.this, REQUEST_MICROPHONE_CODE);
                    } else {//拍照权限
                        PermissionUtil.startApplicationDetailsSettings(ChatActivity.this, REQUEST_CAMERA_CODE);
                    }
//                    for (int i = 0; i < perms.size(); i++) {
//                        if (perms.get(i).endsWith("android.permission.RECORD_AUDIO")) {
//                            PermissionUtil.startApplicationDetailsSettings(ChatActivity.this, REQUEST_MICROPHONE_CODE);
//                        } else if (perms.get(i).endsWith("android.permission.CAMERA")) {
//                            PermissionUtil.startApplicationDetailsSettings(ChatActivity.this, REQUEST_CAMERA_CODE);
//                        }
//                    }
                }
            });
            mTipDialog.show();
        } else {
            ToastUtil.showToast(ChatActivity.this, getString(R.string.tip_permission_reboot_place_holder, tips));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.layout_chat_attention_btn://关注按钮
                FriendDao.getInstance().updateFriendAttentionTag(mFriend.getOwnerId(), mFriend.getUserId(), 1);
                doAddAttention();
                mLayoutAttention.setVisibility(View.GONE);
                break;
            case R.id.img_chat_attention_del://关注删除
                FriendDao.getInstance().updateFriendAttentionTag(mFriend.getOwnerId(), mFriend.getUserId(), 1);
                mLayoutAttention.setVisibility(View.GONE);
                break;
        }
    }


    /**
     * 点击关注
     */
    private void doAddAttention() {

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", mFriend.getUserId());
        DialogHelper.showDefaulteMessageProgressDialog(this);

        // 首先是调接口，
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<AddAttentionResult>(AddAttentionResult.class) {

                    @Override
                    public void onResponse(ObjectResult<AddAttentionResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {

                            if (mFriend.getStatus() == Friend.STATUS_BLACKLIST && mFriend.getIsBeBlack() != 1) {//拉黑与被拉黑
                                mChatBottomView.updateBlack(false);
                            }

                            if (result.getData().getType() == 1 || result.getData().getType() == 3) {// 只是关注的关系
                                mFriendState = 1;
                                // 未回复并且未关注过的发送打招呼消息
                                if (mFriend.getReplyStatus() != Friend.STATUS_REPLAY_BOTH //已回复
                                        && mFriend.getIsBeBlack() != 1 //被拉黑
                                        && result.getData().getIsFollowed() == 0) {// 未被黑，未回复，关注过的发送打招呼消息

                                    doSayHello(coreManager.getSelf().getNickName() + "关注了你");
                                }

                                updateFriendStatus(Friend.STATUS_ATTENTION);
                                FriendDao.getInstance().updateFriendStatus(mFriend.getOwnerId(), mFriend.getUserId(), Friend.STATUS_ATTENTION);

                            } else if (result.getData().getType() == 2 || result.getData().getType() == 4) {// 已经是好友了
                                mFriendState = 2;
                                // 未回复并且未关注过的发送打招呼消息
                                if (mFriend.getReplyStatus() != Friend.STATUS_REPLAY_BOTH
                                        && result.getData().getIsFollowed() == 0) {// 未回复并且未关注过的发送打招呼消息

                                    doSayHello(coreManager.getSelf().getNickName() + "关注了你，你们已经是好友，可以互发语音");
                                }
                                updateFriendStatus(Friend.STATUS_FRIEND);
                                FriendDao.getInstance().updateFriendStatus(mFriend.getOwnerId(), mFriend.getUserId(), Friend.STATUS_FRIEND);
                                mChatBottomView.isFriend(true);
                            } else if (result.getData().getType() == 5) {
                                ToastUtil.showToast(mContext, R.string.add_attention_failed);
                            }
                        } else {
                            Toast.makeText(ChatActivity.this, result.getResultMsg() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(mContext, R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    // 打招呼
    private void doSayHello(String text) {

        ChatMessage sayMessage = new ChatMessage();
        sayMessage.setFromUserId(coreManager.getSelf().getUserId());
        sayMessage.setFromUserName(coreManager.getSelf().getNickName());
        sayMessage.setToUserId(mFriend.getUserId());
        sayMessage.setContent(text);
        sayMessage.setType(XmppMessage.TYPE_TEXT); //文本类型
        sayMessage.setMsgType(ChatMessage.TYPE_HELLO);
        sayMessage.setMySend(true);
//        sayMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
        sayMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
        sayMessage.setTimeSend(TimeUtils.sk_time_current_time());

        mAddhaoyouid = sayMessage.getPacketId();
        ChatMessageDao.getInstance().saveNewSingleChatMessage(mFriend.getOwnerId(), mFriend.getUserId(), sayMessage);
        // 这里最终调用smack的发送消息，
        coreManager.sendChatMessage(mFriend.getUserId(), sayMessage);

        mChatMessages.add(sayMessage);
        mChatContentView.notifyDataSetInvalidated(mChatMessages.size() - 1);

    }

    @Override
    public void onNewFriendSendStateChange(String toUserId, NewFriendMessage message, int messageState) {
        if (messageState == ChatMessageListener.MESSAGE_SEND_SUCCESS) {
            msgSendSuccess(message, message.getPacketId());
        } else if (messageState == ChatMessageListener.MESSAGE_SEND_FAILED) {
            msgSendFailed(message.getPacketId());
        }
    }

    @Override
    public boolean onNewFriend(NewFriendMessage message) {
        return false;
    }

    public void msgSendSuccess(NewFriendMessage message, String packet) {
        if (mAddhaoyouid != null && mAddhaoyouid.equals(packet)) {
            if (mFriendState == 1) {// 关系为关注
                Toast.makeText(getApplicationContext(), InternationalizationHelper.getString("JXAlert_SayHiOK"), Toast.LENGTH_SHORT).show();
                ChatMessage sayChatMessage = new ChatMessage();
                sayChatMessage.setContent(InternationalizationHelper.getString("JXFriendObject_WaitPass"));
                sayChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                // 各种Dao都是本地数据库的操作，
                // 这个是好友表里更新最后一条消息，
                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, sayChatMessage);

                // 这个是新的好友界面用的，等验证什么的都在新的好友页面，
                NewFriendDao.getInstance().changeNewFriendState(mFriend.getUserId(), Friend.STATUS_10);// 好友状态
                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);
            } else if (mFriendState == 2) {//关系为好友
                Toast.makeText(getApplicationContext(), InternationalizationHelper.getString("JX_AddSuccess"), Toast.LENGTH_SHORT).show();

                NewFriendDao.getInstance().ascensionNewFriend(message, Friend.STATUS_FRIEND);
                FriendHelper.addFriendExtraOperation(mLoginUserId, mFriend.getUserId());// 加好友

                ChatMessage addChatMessage = new ChatMessage();
                addChatMessage.setContent(InternationalizationHelper.getString("JXNearVC_AddFriends") + ":" + mFriend.getNickName());
                addChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, addChatMessage);

                NewFriendDao.getInstance().changeNewFriendState(mFriend.getUserId(), Friend.STATUS_22);//添加了xxx
                FriendDao.getInstance().updateFriendContent(mLoginUserId, mFriend.getUserId(), InternationalizationHelper.getString("JXMessageObject_BeFriendAndChat"), XmppMessage.TYPE_TEXT, TimeUtils.sk_time_current_time());
                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

                CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
            }

        }
    }

    public void msgSendFailed(String packet) {
        DialogHelper.dismissProgressDialog();
    }


    /**
     * @param isReset  true 恢复默认设置 drawable =null  false:设置新的背景图
     * @param drawable
     */
    @Override
    public void handle(boolean isReset, Drawable drawable) {
        // 构建Colorful对象
        Colorful mColorful;
        Colorful.Builder builder = new Colorful.Builder(this)
                .textColor(R.id.tv_title_center, R.attr.chat_tv_title)//标题颜色
                .textColor(R.id.tv_online, R.attr.chat_tv_online)//在线字体颜色
                .imageViewbgDrawable(R.id.iv_title_left, R.attr.chat_iv_back)//返回图标
                .imageViewbgDrawable(R.id.iv_title_right, R.attr.chat_iv_more)//更多图标
                .backgroundColor(R.id.rl_chat_list, R.attr.chat_msg_list_bg)// 聊天列表

                .imageViewbgDrawable(R.id.voice_img_btn, R.attr.chat_bottom_bar_voice)//底部语音按钮图标
                .imageViewbgDrawable(R.id.img_bottom_photo, R.attr.chat_bottom_bar_picture)//更多图标
                .imageViewbgDrawable(R.id.img_bottom_camera, R.attr.chat_bottom_bar_camera)//底部拍照按钮图标
                .imageViewbgDrawable(R.id.emotion_btn, R.attr.chat_bottom_bar_emoji)//emoji图标
                .imageViewbgDrawable(R.id.more_btn, R.attr.chat_bottom_bar_more)//更多图标
                .imageViewbgDrawable(R.id.img_msg_send, R.attr.chat_bottom_bar_send);//发送消息按钮
        if (isReset) {
            Log.e("lzs", "isReset");
            //深色状态栏字体图标
            StatusBarCompat.setLightStatusBar(getWindow(), true);
            mColorful = builder.backgroundColor(R.id.mergerStatus, R.attr.chat_toolbar_bg) //标题栏背景
                    .backgroundColor(R.id.rl_chat_meun, R.attr.chat_bottom_bg)//底部背景
                    .create();
            mColorful.setTheme(R.style.chat_style_dark);
            findViewById(R.id.root_view).setBackground(null);
        } else {
            //浅色状态栏字体图标
            Log.e("lzs", "setBackground");
            StatusBarCompat.setLightStatusBar(getWindow(), false);
            mColorful = builder.backgroundDrawable(R.id.mergerStatus, R.attr.chat_toolbar_bg)//标题栏背景
                    .backgroundDrawable(R.id.rl_chat_meun, R.attr.chat_bottom_bg)//底部背景
                    .create();
            mColorful.setTheme(R.style.chat_style_light);
            findViewById(R.id.root_view).setBackground(drawable);
        }
    }
}
